package handlers

import (
	"git.hortorgames.com/orange/tang/log"
	"git.hortorgames.com/serverless/htgserver/apiserver"
	"git.hortorgames.com/serverless/htgserver/apiserver/services"
	"git.hortorgames.com/serverless/htgserver/consts"
	"strings"
)

type MidFindGame struct {
	Base
}

func NewMidFindGame(server *apiserver.Server) *MidFindGame {
	h := &MidFindGame{}
	h.Server = server
	return h
}

//type reqFindGame struct {
//	GameId *string `json:"gameId,omitempty"`
//}

//@httpMid:""
func (h *MidFindGame) Run(ctx *apiserver.Context) {
	if ctx.RequestData.GameId == "" {
		ctx.Logger().Error("gameId is empty")
		h.Halt(ctx, consts.ErrorInvalidParameter)
		ctx.Abort()
		return
	}
	game := services.Game.FindGame(h.Server.InternalApiClient, ctx.RequestData.GameId)
	if game == nil {
		ctx.Logger().Error("game not found", "gameId", ctx.RequestData.GameId)
		h.Halt(ctx, consts.ErrorNotFoundData)
		ctx.Abort()
		return
	}
	logPrj := game.LogProject
	if logPrj == "" {
		logPrj = strings.ToLower(game.Team)
	}
	logStore := game.LogStore
	if logStore == "" {
		logStore = strings.ToLower(game.Id)
	}
	ctx.SetLogger(log.WithProjectAndLogStore(logPrj, logStore).With("api", ctx.Request().URL.Path, "playerId", ctx.RequestData.PlayerId, "seq", ctx.RequestData.Seq, "token", ctx.RequestData.Token))
	ctx.Game = game
	ctx.Next()
}
